﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace LastfmTopDownloader
{
    public partial class StatusForm : Form
    {
        private BackgroundWorker _backgroundWorker;

        private string _artist;
        private List<string> _songs;

        private const string StatusWaiting = "Wait";
        private const string StatusFail = "Fail";
        private const string StatusDownloading = "Downloading";
        private const string StatusDone = "Done";

        public StatusForm(string artist)
        {
            _artist = artist;
            InitializeComponent();

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += DoWork;
        }

        void DoWork(object sender, DoWorkEventArgs eventArgs)
        {
            toolStripStatusLabel1.Text = "Получаем список песен";
            _songs = VkDownloader.GetSongs(_artist);
            FillData(_songs);
            toolStripStatusLabel1.Text = "Проверяем наличие песен Вконтакте";
            UpdateStatus(VkDownloader.GetFailedSongs(_songs,_artist), StatusFail);
            toolStripStatusLabel1.Text = "Загружаем песни";
            VkDownloader.DownloadedEvent += VkDownloaderDownloadedEvent;
            VkDownloader.DownloadingEvent += VkDownloaderDownloadingEvent;
            VkDownloader.FaildeEvent += VkDownloaderOnFaildeEvent;
            VkDownloader.GetUris(_artist);
            toolStripStatusLabel1.Text = "Готово";
            MessageBox.Show("Загрузка завершена", "", MessageBoxButtons.OK);
            
        }

        private void VkDownloaderOnFaildeEvent(string song)
        {
            UpdateStatus(song, StatusFail);
        }

        void VkDownloaderDownloadingEvent(string song)
        {
            UpdateStatus(song, StatusDownloading);
        }

        void VkDownloaderDownloadedEvent(string song)
        {
            UpdateStatus(song, StatusDone);
        }

        private void FillData(List<string> songs)
        {
            Action addData = delegate
                                 {
                                     
                                     foreach (var s in songs)
                                     {
                                         statusDataGridView1.Rows.Add(s, StatusWaiting);
                                     } 
                                 };
            if (!statusDataGridView1.InvokeRequired)
                addData();
            else
                statusDataGridView1.Invoke(addData);
        }

        private void UpdateStatus(List< string> songNames, string status)
        {
            if (songNames == null) throw new ArgumentNullException("songNames");

            if (songNames.Count > 0)
            {
                Action updateStatus = delegate
                                          {
                                              foreach (
                                                  var row in
                                                      songNames.Select(
                                                          songName =>
                                                          (from DataGridViewRow row in statusDataGridView1.Rows
                                                           where row.Cells["Song"].Value.ToString().Equals(songName)
                                                           select row)).SelectMany(rows => rows))
                                              {
                                                  row.Cells[1].Value = status;
                                              }
                                          };
                if (!statusDataGridView1.InvokeRequired)
                    updateStatus();
                else
                    statusDataGridView1.Invoke(updateStatus);
            }
        }

        private void UpdateStatus(string songName, string status)
        {
            Action updateStatus = delegate
                                      {

                                          var rows = from DataGridViewRow row in statusDataGridView1.Rows
                                                     where row.Cells["Song"].Value.ToString().Equals(songName)
                                                     select row;
                                          foreach (var dataGridViewRow in rows)
                                          {
                                              dataGridViewRow.Cells[1].Value = status;
                                          }

                                      };
            if (!statusDataGridView1.InvokeRequired)
                updateStatus();
            else
                statusDataGridView1.Invoke(updateStatus);

        }

        public void WriteTable()
        {
            _backgroundWorker.RunWorkerAsync();
        }
    }
}
